package com.lrs.java.jdbc.jdbc_teacher;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class EmpTree {
	public static void main(String[] args){
		new EmpTree().show();
	}
	
	public void show() {
		
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");

			conn = DriverManager
					.getConnection("jdbc:oracle:thin:@localhost:1521:ZLPD", "scott", "tiger");
			stmt = conn.createStatement();
			rs = stmt.executeQuery("select * from emp where mgr is null");
			if(rs.next()) {
				System.out.println(rs.getString("ename"));
				tree(conn, rs.getInt("empno"), 0);
			}
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException ex) {
			System.out.println("SQLException: " + ex.getMessage());
			System.out.println("SQLState: " + ex.getSQLState());
			System.out.println("VendorError: " + ex.getErrorCode());
		} finally {
			
			try {
				if (rs != null) {
					rs.close();
					rs = null;
				}
				if (stmt != null) {
					stmt.close();
					stmt = null;
				}
				if(conn != null) {
					conn.close();
					conn = null;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	private void tree(Connection conn, int empno, int grade) {
		Statement stmt = null;
		ResultSet rs = null;
		
		StringBuilder strPre = new StringBuilder();
		for(int i=0; i<grade; i++) {
			strPre.append("    ");
		}
		
		try {
			stmt = conn.createStatement();
			rs = stmt.executeQuery("select * from emp where mgr = " + empno);
			
			while(rs.next()) {
				System.out.println(strPre + rs.getString("ename"));
				tree(conn, rs.getInt("empno"), grade + 1);
				
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (rs != null) {
					rs.close();
					rs = null;
				}
				if (stmt != null) {
					stmt.close();
					stmt = null;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
	}
}